package com.aiYouPms.common.service.impl;

import com.aiYouPms.common.dao.AdminUserRoleDao;
import com.aiYouPms.common.dao.RoleDao;
import com.aiYouPms.common.model.Role;
import com.aiYouPms.common.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class RoleServiceImpl implements RoleService {

    private final RoleDao roleDao;
    private final AdminUserRoleDao adminUserRoleDao;

    @Autowired
    public RoleServiceImpl(RoleDao roleDao, AdminUserRoleDao adminUserRoleDao) {
        this.roleDao = roleDao;
        this.adminUserRoleDao = adminUserRoleDao;
    }

    @Override
    public List<Role> findAll() {
        return roleDao.findAll();
    }

    @Override
    public Role findById(Integer id) {
        return roleDao.findById(id);
    }

    @Override
    public Role findByRoleName(String roleName) {

        return roleDao.findByRoleName(roleName);
    }
    @Override
    public Role findByRoleCode(String roleCode) {
        return roleDao.findByRoleCode(roleCode);
    }

    @Override
    @Transactional
    public Role create(Role role) {
        long currentTime = System.currentTimeMillis() / 1000;
        Role existingRole = roleDao.findByRoleName(role.getRoleName());
        if (existingRole != null) {
            throw new RuntimeException("角色已存在");
        }
        role.setCreatedAt((int) currentTime);
        role.setUpdatedAt((int) currentTime);
        roleDao.insert(role);
        return role;
    }

    @Override
    @Transactional
    public Role update(Integer id, Role role) {
        Role existingRole = roleDao.findById(id);
        if (existingRole == null) {
            throw new RuntimeException("角色不存在");
        }
        
        role.setId(id);
        long currentTime = System.currentTimeMillis() / 1000;
        role.setUpdatedAt((int) currentTime);
        roleDao.update(role);
        return role;
    }

    @Override
    @Transactional
    public void deleteById(Integer id) {
        Role existingRole = roleDao.findById(id);
        if (existingRole == null) {
            throw new RuntimeException("角色不存在");
        }

        Role exitAdminUser=adminUserRoleDao.findRoleById(id);
        if (exitAdminUser != null) {
            throw new RuntimeException("该角色下有管理员用户，无法删除");
        }
        roleDao.deleteById(id);
    }

    @Override
    public List<Role> search(Role role) {
        return roleDao.search(role);
    }


}